package com.icloud.system.boot.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.icloud.common.core.api.ResultCode;
import com.icloud.common.database.mapper.AppCustomerAuthMapper;
import com.icloud.common.database.mapper.AppCustomerMapper;
import com.icloud.common.database.model.AppCustomer;
import com.icloud.common.database.model.AppCustomerAuth;
import com.icloud.common.web.exception.ApiException;
import com.warrenstrange.googleauth.ICredentialRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository(value = "credentialRepository")
public class GoogleAuthCredentialRepository implements ICredentialRepository {
    @Autowired
    private AppCustomerMapper appCustomerMapper;
    @Autowired
    private AppCustomerAuthMapper appCustomerAuthMapper;

    @Override
    public String getSecretKey(String userName) {
        AppCustomer appCustomer = appCustomerMapper.selectOne(new LambdaQueryWrapper<AppCustomer>().eq(AppCustomer::getUsername, userName));
        if(appCustomer!=null){
            Long customerId = appCustomer.getId();
            AppCustomerAuth appCustomerAuth = appCustomerAuthMapper.selectOne(new LambdaQueryWrapper<AppCustomerAuth>().eq(AppCustomerAuth::getCustomerId, customerId));
            if(appCustomerAuth==null){
                throw new ApiException(ResultCode.FAILED);
            }
            return appCustomerAuth.getTwoFactorKey();
        }else{
            throw new ApiException(ResultCode.FAILED);
        }
    }

    @Override
    public void saveUserCredentials(String userName, String secretKey, int validationCode, List<Integer> scratchCodes) {
        AppCustomer appCustomer = appCustomerMapper.selectOne(new LambdaQueryWrapper<AppCustomer>().eq(AppCustomer::getUsername, userName));
        if(appCustomer!=null){
            Long customerId = appCustomer.getId();
            AppCustomerAuth appCustomerAuth = appCustomerAuthMapper.selectOne(new LambdaQueryWrapper<AppCustomerAuth>().eq(AppCustomerAuth::getCustomerId, customerId));
            if(appCustomerAuth==null){
                throw new ApiException(ResultCode.FAILED);
            }
            AppCustomerAuth updateAuth = new AppCustomerAuth();
            updateAuth.setId(appCustomerAuth.getId());
            updateAuth.setTwoFactorKey(secretKey);
            appCustomerAuthMapper.updateById(updateAuth);
        }
    }
}
